<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <div class="upload_elements">
    <div class="steps">
      <el-steps :active="active" style="width: 100%" align-center>
        <el-step title="基本信息设置" />
        <el-step title="数据上传" />
        <el-step title="数据质量检测" />
        <el-step title="完成" />
      </el-steps>
    </div>
    <div class="base-info" v-show="active === 1" v-loading="uploadLoading" element-loading-text="压缩包解压中...">
      <TabsModel ref="tabsModelRef" />
    </div>
    <div v-loading="uploadLoading" element-loading-text="确认上传中..." class="upload_json" v-show="active === 2">
      <UploadJson ref="uploadJsonRef" />
       
      <!-- <CodeEditor 
        :height="editorHeight"
        class="editor"
      />
      <el-button type="primary" @click="uploadFile" size="small">执 行</el-button> -->
    </div>
    <div class="upload_list" v-show="active === 3" v-loading="uploadLoading" element-loading-text="数据导入中...">
      <Result ref="checkResultRef" />
    </div>
    <div class="upload_success" v-show="active === 4">
      <div class="upload_success_message">
        <el-icon size="48" color="#67C23A"><CircleCheck /></el-icon>
        <h3 class="res-statistic">
          数据导入成功！
        </h3>
        <h3 class="res-statistic">
          本次共导入 <el-link type="primary">{{ importFileResult?.totalDataCount }}</el-link> 条数据。
        </h3>
      </div>
    </div>
    <div class="option_btn">
      <el-button size="small" @click="cancel" v-show="active === 1" :disabled="uploadLoading">取消</el-button>
      <!-- <el-button size="small" type="primary" @click="exportExcel" v-show="active === 2">导出数据</el-button> -->
      <el-button size="small" :disabled="uploadLoading" v-show="[2,3,4].includes(active)" @click="step('pre', 1)">上一步</el-button>
      <el-button size="small" type="primary" :disabled="uploadLoading" v-show="active === 3" @click="step('next', 3)">确认上传</el-button>
      <el-button size="small" type="primary" :disabled="uploadLoading" v-show="[1,2].includes(active)" @click="step('next', 2)">下一步</el-button>
      <el-button size="small" type="primary" v-show="active === 4" @click="finish">完成</el-button>
    </div>
    <el-dialog v-model="dialogFormVisible" title="文件解析中..." width="500" :show-close="false">
      <el-table v-loading="dialogFormVisible" :data="[]" style="width: 100%">
      </el-table>
      <p style="text-align: center;">文件解析中，请耐心等待。</p>
    </el-dialog>
  </div>
</template>
<script  setup name="ImportModelData">
import DataHandle from './DataHandle.vue';
import DataTransform from './DataTransform.vue';
import ResultTreeTable from './ResultTreeTable.vue';
import TabsModel from "../materialWarehouse/TabsModel.vue";
import UploadJson from "../materialWarehouse/UploadJson.vue";
import Result from "../materialWarehouse/Result.vue";
import CodeEditor from "@/components/CodeEditor";
import { checkMaterialDataImport, confirmMaterialDataImport, getDatabaseModelCardDetail } from '@/api/dataAcquisition';

const emits = defineEmits(['handleEvent']);
const props = defineProps(['modelId']);
const fullscreenLoading = ref(false);
const uploadLoading = ref(false);
const active = ref(1);
const tabsModelRef = ref();
const uploadJsonRef = ref();
const checkResultRef = ref();
const chooseData = ref(null);
const computedData = ref(null);
const importFileResult = ref({});
const checkedTreeData = ref([]);
const computedUpdate = ref(false);
const directoryPath = ref('');
const dialogFormVisible = ref(false);
// 导入确认数据
const confirmImportTableData = ref([]);
const notFilterCount = ref(0);
const totalCount = ref(0);
// code editor
const code = ref(`// 输入你的代码
function hello() {
  console.log('Hello CodeMirror!')
}`)
const editorHeight = ref('calc(100vh - 191px)');
/**
   * 将文件转换成md5并进行切片
   * @returns md5
   */
   const md5File = (file) => {
    return new Promise((resolve, reject) => {
      // 文件截取
      let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
        chunkSize = file?.size / 100,
        spark = new SparkMD5.ArrayBuffer(),
        fileReader = new FileReader();

      fileReader.onload = function (e) {
        console.log('read chunk nr', checkCurrentChunk + 1, 'of', chunks);
        spark.append(e.target.result);
        checkCurrentChunk += 1;

        if (checkCurrentChunk < chunks) {
          loadNext();
        } else {
          let result = spark.end()
          resolve(result)
        }
      };

      fileReader.onerror = function () {
        message.error('文件读取错误')
      };

      const loadNext = () => {
        const start = checkCurrentChunk * chunkSize,
          end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;

        // 文件切片
        fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
        // 检查进度条
        dispatch({ type: 'check', checkPercent: checkCurrentChunk + 1 })
      }

      loadNext();
    })
    
  }



const step = async (type) => {
  if (type === 'next') {
    if (active.value === 1) {
      try {
        let f1 = await tabsModelRef.value.form1Ref.validate()
        let f2 = await tabsModelRef.value.form2Ref.validate()
        if (!f1 || !f2) {
          return;
        }
        active.value++;
        uploadJsonRef.value.handleData(tabsModelRef.value.infoForm.modelId);
        return;
      } catch (errors) {
        // 处理错误
        console.error('验证失败:', errors);
      }
    }
    if (active.value === 2) {
      checkMaterial()
      return;
    }
    if (active.value === 3) {
      if (importFileResult.value?.failedDataCount > 0) {
        ElMessage({ showClose: true, message: '数据检测失败，请确认后重新上传。', type: 'error' });
        return;
      }
      comfirmImport();
      return;
    }
   
  } else {
    active.value--;
  }
};
// 确认上传
const comfirmImport = () => {
  uploadLoading.value = true;
  confirmMaterialDataImport({
    ...tabsModelRef.value.infoForm,
    directoryPath: directoryPath.value,
    fileSize: importFileResult.value.fileSize,
    algorithmConfigId: uploadJsonRef.value.algorithmConfigId,
    importMethod: uploadJsonRef.value.loadFileType,
  }).then(res => {
    ElMessage({ showClose: true, message: '导入成功', type: 'success' });
    uploadLoading.value = false;
    active.value ++;
  }).catch(() => {
    uploadLoading.value = false;
  }).finally(() => {
    uploadLoading.value = false;
  })
}
// 文件上传解析
const checkMaterial = () => {
  if (uploadJsonRef.value.uploadFiles.length === 0) {
    ElMessage({ showClose: true, message: '文件为空，请重新上传。', type: 'error' });
    return; 
  }
  if (uploadJsonRef.value.loadFileType == 'EXCEL导入' && !uploadJsonRef.value.algorithmConfigId) {
    ElMessage({ showClose: true, message: '请选择算法！', type: 'error' });
    return; 
  }
  uploadLoading.value = true;
  let fd = new FormData();
  console.log('uploadJsonRef.value.uploadFiles')
  fd.append('file', uploadJsonRef.value.uploadFiles[0]);
  fd.append('importMethod', uploadJsonRef.value.loadFileType);
  fd.append('modelId', tabsModelRef.value.infoForm.modelId);
  checkMaterialDataImport(fd).then(res => {
    if (res) {
      importFileResult.value = res.data;
      directoryPath.value = res.data.directoryPath;
      active.value++;
      checkResultRef.value.handleData(res.data)
      uploadLoading.value = false;
    }
  }).finally(() => {
    uploadLoading.value = false;
  })
}
const handleEvent = (data) => {
  if (data?.type === 'choose') {
    chooseData.value = data?.data || [];
    checkedTreeData.value = data?.treeData || [];
    computedUpdate.value = true;
    nextTick(() => {
      computedUpdate.value = false;
    });
  }
  if (data?.type === 'computed') {
    computedData.value = data?.data || [];
  }
  if (data?.type === 'confirmImport') {
    confirmImportTableData.value = data?.data?.tableData || [];
  }
};
// 初始化模型卡片基础信息
const initCardInfo = (modelId) => {
  getDatabaseModelCardDetail({modelId}).then(res => {
    if (res) {
      tabsModelRef.value.initCardInfo(res.data);
    } 
  })
}
// 完成组建
const finish = () => {
  emits('handleEvent', { component: 'MaterialList', type: 'finish', modelId: props.modelId });
};
// 取消
const cancel = () => {
  emits('handleEvent', { component: 'MaterialList', type: 'cancel', modelId: props.modelId });
};
onMounted(() => {
  props.modelId && initCardInfo(props.modelId);
});
</script>
<style lang="scss" scoped>
.upload_json {
  // width: 100%;
  // height: calc(100vh - 245px);
  // display: flex;
  // align-items: center;
  // flex-direction: column;
  // padding: 50px 0;
  .el-upload__text {
    font-size: 14px;
  }
}
.upload_elements {
  padding: 10px;
  width: 100%;
  height: calc(100vh - 84px);
  display: flex;
  flex-direction: column;
  align-items: center;
  overflow: scroll;
  font-size: 12px;
  .steps {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 30px;
  }
  .upload {
    width: 800px;
    margin-top: 20px;
    .upload_content {
      width: 800px;
      height: 475px;
      text-align: center;
      .upload_form {
        margin-top: 20px;
        display: flex;
        flex-direction: column;
        align-items: center;
      }
    }
  }
  .upload_list,
  .upload_success {
    margin-top: 10px;
    // overflow: scroll;
    // min-height: calc(100vh - 251px);
    width: 100%;
  }
  .model-batch {
    padding: 10px;
    label {
      font-size: 16px;
    }
    span {
      margin-right: 20px;
      font-size: 14px;
    }
  }
  .option_btn {
    margin-top: 20px;
  }
  .upload_success {
    margin-top: 10px;
    .upload_success_message {
      margin-bottom: 10px;
      display: flex;
      flex-direction: column;
      align-items: center;
    }
  }
  .finish {
    width: 600px;
    margin-top: 20px;
  }
  :deep(.el-step__title) {
    font-size: 12px;
  }
}
</style>
